package com.caigou.controller.front;

import com.alibaba.fastjson.JSONObject;
import com.caigou.bean.cms.param.FrontSurveyParam;
import com.caigou.component.RedisStringComponent;
import com.caigou.component.RequestComponent;
import com.caigou.service.ISurveyService;
import com.caigou.service.SurveyCatalogService;
import com.caigou.util.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/front/survey/")
public class FrontSurveyController {

    @Resource
    private RedisStringComponent redisStringComponent;

    @Resource
    private ISurveyService surveyService;
    @Resource
    private SurveyCatalogService surveyCatalogService;

    @ApiOperation("获取智能表单目录页数据(无需验证)")
    @PostMapping("loadSurveyCatalogData")
    public Result loadSurveyCatalogData(@RequestBody FrontSurveyParam param, HttpServletRequest request){
        return surveyCatalogService.loadSurveyCatalogData(param,request);
    }

    @ApiOperation("智能表单表单状态验证(如使用目录或表单设置、验证码、开放时间段、登录验证等)")
    @PostMapping("verifySurveyForm")
    public Result verifySurveyForm(@RequestBody FrontSurveyParam param, HttpServletRequest request){
        return surveyCatalogService.verifySurveyForm(param,request);
    }

    /**
     * 根据formId判断该表单是否需要登录
     * @param param
     * @return
     */
    @PostMapping("verifySurveyFormNeedLogin")
    public Result verifySurveyFormNeedLogin(@RequestBody FrontSurveyParam param){
        return surveyCatalogService.verifySurveyFormNeedLogin(param);
    }

    @PostMapping("verifySurveyFormNeedLogin2")
    public Result verifySurveyFormNeedLogin2(@RequestParam(value="formId", required=true) String formId){
        FrontSurveyParam param = new FrontSurveyParam();
        param.setFormId(formId);
        return surveyCatalogService.verifySurveyFormNeedLogin(param);
    }

    @ApiOperation("填写智能表单邀请码")
    @PostMapping("verifySurveyFormCode")
    public Result verifySurveyFormCode(@RequestBody FrontSurveyParam param, HttpServletRequest request){
        return surveyCatalogService.verifySurveyFormCode(param,request);
    }

    @ApiOperation("验证通过，获取表单详情页数据")
    @PostMapping("loadSurveyFormData")
    public Result loadSurveyFormData(@RequestBody FrontSurveyParam param, HttpServletRequest request){
        return surveyService.loadSurveyFormData(param,request);
    }

    @ApiOperation("获取表单选项详情页数据")
    @PostMapping("loadSurveyFormOptionData")
    public Result loadSurveyFormOptionData(@RequestBody FrontSurveyParam param, HttpServletRequest request){
        return surveyService.loadSurveyFormOptionData(param,request);
    }

    @ApiOperation("提交表单接口")
    @PostMapping("submitFormAnswer")
    public Result submitFormAnswer(@RequestBody FrontSurveyParam param, HttpServletRequest request){
        return surveyService.submitFormAnswer(param,request);
    }

    @ApiOperation("获取系统时间戳")
    @PostMapping("loadSystemTime")
    public Result loadSystemTime(){
        return Result.success(System.currentTimeMillis()/1000);
    }

    @ApiOperation("获取微信调起APP参数信息")
    @PostMapping("loadAppTunedUpInfo")
    public Result loadAppTunedUpInfo(String url){
        // 请求token
        String token = redisStringComponent.get("wx_access_token");
        log.info("redisToken ={}", token);
        if (null == token || ("").equals(token)){
            log.info("没有从缓存中获取到token的值改为直接请求微信获取");
            String tokenResponse = RequestComponent.HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx20c094354adc43d6&secret=14ce3bf116a1866e905d61ece6306bca");
            log.info("tokenResponse ={}", tokenResponse);
            if (null != tokenResponse){
                JSONObject tokenJSON = JSONObject.parseObject(tokenResponse);
                token = tokenJSON.getString("access_token");
                redisStringComponent.setEx("wx_access_token", token, 7000, TimeUnit.SECONDS);
            }
        }
        Map<String, String> map = new HashMap<>();
        // 请求ticket
        String ticketResponse = RequestComponent.HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi");
        log.info("ticketResponse ={}", ticketResponse);
        if (null != ticketResponse){
            JSONObject ticketJSON = JSONObject.parseObject(ticketResponse);
            if (ticketJSON.getString("errcode").equals("40001")){
                log.info("缓存已失效，需要进行重新请求");
                String tokenResponse = RequestComponent.HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx20c094354adc43d6&secret=14ce3bf116a1866e905d61ece6306bca");
                JSONObject tokenJSON = JSONObject.parseObject(tokenResponse);
                token = tokenJSON.getString("access_token");
                redisStringComponent.setEx("wx_access_token", token, 7000, TimeUnit.SECONDS);
                ticketResponse = RequestComponent.HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi");
                ticketJSON = JSONObject.parseObject(ticketResponse);
            }
            String ticket = ticketJSON.getString("ticket");
            map.put("ticket",ticket);
            String noncestr = String.valueOf((System.currentTimeMillis() / 1000));
            map.put("noncestr",noncestr);
            String timestamp = String.valueOf((System.currentTimeMillis() / 1000));
            map.put("timestamp", timestamp);
            map.put("url",url);
            String signStr = "jsapi_ticket="+ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
            String sign = DigestUtils.shaHex(signStr);
            log.info("sign={}",sign);
            map.put("sign",sign);
        }
        return Result.success(map);
    }

    @ApiOperation("验证用户是否提交过表单")
    @PostMapping("loadUserIsSubmit")
    public Result loadUserIsSubmit(@RequestBody FrontSurveyParam param){
        return surveyService.loadUserIsSubmit(param);
    }
}
